package delegate4j;

import com.sun.istack.internal.Nullable;

import java.util.ArrayList;
import java.util.concurrent.FutureTask;

public final class EventHandler<S extends EventArgs> extends Delegate<IEventHandler<S>> {
    public EventHandler(IEventHandler<S> delegate) {
        super(delegate);
    }

    public void invoke(@Nullable Object sender, @Nullable S data) throws Exception{
        for (IEventHandler<S> eventHandler : delegates) {
            eventHandler.invoke(sender, data);
        }
    }

    public AsyncResult<Void> invokeAsync(@Nullable Object sender, @Nullable S data, @Nullable AsyncDelegateCallback callback) throws Exception {
        ArrayList<FutureTask<Void>> tasks = new ArrayList<>();
        for (int i = 0; i < delegates.size(); i++) {
            tasks.add(delegates.get(i).invokeAsync(sender, data, callback));
        }

        waitTasksFinish(tasks, new Object[]{data}, callback);

        //返回tasks的浅拷贝
        return new AsyncResult<>(tasks);
    }
}
